package com.baoxin.chenxixc4coach;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.baoxin.chenxixc4coach.utils.TimeTools;

import org.json.JSONObject;

public class RegisterActivity extends BaseActivity {

    private EditText mPhone;
    private EditText mVerification;
    private EditText mPassword;
    private EditText mPassword2;
    private CheckBox mAgree;
    private Button mCountDown;
    private Button mRegister;
    private View mRegisterFormView;
    private View mProgressView;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) toolbar.getLayoutParams();
        lp.topMargin = getStatusBarHeight();
        toolbar.setLayoutParams(lp);
        //在setSupportActionBar之后才有效
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView tips = findViewById(R.id.tips);
        SpannableString spannableString = new SpannableString("我已阅读并同意《晨习服务协议》");

        MyClickableSpan clickableSpan = new MyClickableSpan();
        spannableString.setSpan(clickableSpan, 8, 14, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tips.setMovementMethod(LinkMovementMethod.getInstance());
        tips.setHighlightColor(Color.parseColor("#00ffffff"));
        tips.setText(spannableString);

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case Msg.GET_VERIFICATION_SUCCEED:
                        Toast.makeText(RegisterActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                        break;
                    case Msg.GET_VERIFICATION_FAILED:
                        Toast.makeText(RegisterActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                        break;
                    case Msg.REGISTER_SUCCEED:
                        Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case Msg.REGISTER_FAILED:
                        showProgress(false);
                        break;
                }
            }
        };
        mRegisterFormView = findViewById(R.id.register_form);
        mProgressView = findViewById(R.id.register_progress);
        mPhone = findViewById(R.id.phone_et);
        mVerification = findViewById(R.id.verification_et);
        mPassword = findViewById(R.id.password_et);
        mPassword2 = findViewById(R.id.password2_et);
        mAgree = findViewById(R.id.agree);
        mCountDown = findViewById(R.id.countDown_bt);
        mRegister = findViewById(R.id.register_bt);
        mAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mRegister.setEnabled(true);
                } else {
                    mRegister.setEnabled(false);
                }
            }
        });

        //检测2个密码是否一致
        mPassword2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) return;
                String psd = mPassword.getText().toString();
                String psd2 = mPassword2.getText().toString();
                if (!psd.equals(psd2)) {
                    Toast.makeText(RegisterActivity.this, "密码不一致", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        uiOpions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        super.onStart();
    }

    boolean isSendMsgCd = false;


    //获取验证码
    public void onGetVerification(View view) {
        if (isSendMsgCd) {
            return;
        }
        String phone = mPhone.getText().toString();
        if (phone.length() != 11) {
            Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        CountDownTimer countDownTimer = new CountDownTimer(59 * 1000 + 999, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mCountDown.setText(TimeTools.getSecondByLong(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                mCountDown.setText("重新获取");
                isSendMsgCd = false;
            }
        };

        try {
            JSONObject body = new JSONObject();
            body.put("phone", mPhone.getText().toString());
            NetUtil.post(this, Interfaces.URL_GETVIFICATION_CODE, body.toString(),
                    new MyCallback(Interfaces.URL_GETVIFICATION_CODE, handler));


        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        countDownTimer.start();
        isSendMsgCd = true;
    }

    //注册
    public void onRegister(View view) {
        String error = "";

        String psd = mPassword.getText().toString();
        String psd2 = mPassword2.getText().toString();
        if (!psd.equals(psd2)) {
            error = "密码不一致";
        }
        if (psd.length() < 6) {
            error = "密码过短";
        }

        if (mVerification.getText().length() == 0) {
            error = "请输入验证码";
        }

        if (mPhone.getText().length() != 11) {
            error = "手机号格式错误";
        }
        if (error.length() > 0) {
            Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
        } else {
            showProgress(true);

            JSONObject body = new JSONObject();
            try {
                body.put("phone", mPhone.getText().toString());
                body.put("code", mVerification.getText().toString());
                body.put("password", mPassword2.getText().toString());
                body.put("type", 0);
                NetUtil.post(this, Interfaces.URL_REGISTER, body.toString(),
                        new MyCallback(Interfaces.URL_REGISTER, handler));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public void switchToLogin(View view) {

        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
    }


    private void showProgress(final boolean show) {

        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mRegisterFormView.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
        mRegisterFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mRegisterFormView.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });

    }


    class MyClickableSpan extends ClickableSpan {

        @Override
        public void onClick(View widget) {
            Intent intent = new Intent(RegisterActivity.this, AgreementActivity.class);
            startActivity(intent);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.colorLightBlue));
            ds.setUnderlineText(false);
        }
    }
}
